package com.system.server;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.sql.ResultSet;
import java.sql.SQLException;

public class ServerThread extends Thread{
    private Socket socket;
    InputStream in;
    OutputStream out;
    public String finalInformation;
    MainUI mainUI=null;

    public ServerThread(Socket socket) {
        this.socket=socket;
        //this.mainUI=mainUI;
    }

    public void run() {
        try{
            while(true){
                //System.out.println(socket);
                in=socket.getInputStream();
                byte[] bytes=new byte[1024];
                in.read(bytes);
                String str=new String(bytes);
                System.out.println(str);
                processing(str);

                out=socket.getOutputStream();
                out.write(finalInformation.getBytes());
                if(finalInformation!=null)
                    finalInformation=null;
            }
        }catch (Exception e){
            System.out.println("服务端断开连接");
            this.interrupt();
            e.printStackTrace();
        }

        try{
            socket.close();
            System.out.println("服务端主动断开连接");
            this.interrupt();

        }catch (IOException e){
            System.out.println("服务端关闭连接出现异常");
            e.printStackTrace();
            this.interrupt();
        }
    }

    public void processing(String message) {
        String[] info_Request=message.split("/");
        if(info_Request[0].equals("L"))
            finalInformation=loginInfo(info_Request);
        if(info_Request[0].equals("R"))
            finalInformation=registerInfo(info_Request);
        if(info_Request[0].equals("P"))
            finalInformation=updatePassword(info_Request);
        if(info_Request[0].equals("A"))
            finalInformation=updateAddress(info_Request);
        if(info_Request[0].equals("E"))
            finalInformation=updateEmail(info_Request);
        if(info_Request[0].equals("T"))
            finalInformation=updateText(info_Request);
        if(info_Request[0].equals("N"))
            finalInformation=updateNickName(info_Request);
        if(info_Request[0].equals("F"))
            finalInformation=getMessage(info_Request);
        if(info_Request[0].equals("M"))
            finalInformation=updateMoney(info_Request);
        if(info_Request[0].equals("MP"))
            finalInformation=Pay(info_Request);
        if(info_Request[0].equals("FS"))
            finalInformation=FoodShow(info_Request);
        if(info_Request[0].equals("NP"))
            finalInformation=getRowOfFood();
        if(info_Request[0].equals("SP"))
            finalInformation=getCarFoodNum(info_Request);
        if(info_Request[0].equals("SI"))
            finalInformation=addShopCar(info_Request);
        if(info_Request[0].equals("SFS"))
            finalInformation=getCarFoodInfo(info_Request);
        if(info_Request[0].equals("B"))
            finalInformation=PayInShopCar(info_Request);
        if(info_Request[0].equals("U"))
            finalInformation=getUrl(info_Request);

    }

    //处理前端请求，返回登录结果
    public String loginInfo(String[] info){
        String userName=info[1];
        String userPassword=info[2];
        ResultSet res=UserDAO.selectWithName(userName);

        try{
            while(res.next()){
                if(userName.equals(res.getString("user_name"))&&userPassword.equals(res.getString("user_password"))){
                    //mainUI.add(userName+"登录成功");
                    return "A";
                }
                else{
                    //mainUI.add(userName+"登陆失败");
                    return "F";
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        //mainUI.add(userName+"不存在");
        return "N";
    }

    //处理前端请求，返回注册结果
    public String registerInfo(String[] info){
        String userName=info[1];
        String password=info[2];
        String email=info[3];
        ResultSet res=UserDAO.selectWithName(userName);

        try{
            while(res.next()){
                if(userName.equals(res.getString("user_name"))){
                    //mainUI.add(userName+"已存在，注册失败");
                    return "F";
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        User newUser=new User(userName,password,email);
        UserDAO.insert(newUser);
        //mainUI.add(userName+"注册成功");
        return "B";
    }

    //修改密码
    public String updatePassword(String[] info){
        String userName=info[1].trim();
        String newPassword=info[2].trim();

        UserDAO.updatePassword(userName,newPassword);
        //mainUI.add(userName+"修改密码");
        return "S";
    }

    //修改地址
    public String updateAddress(String[] info){
        String userName=info[1].trim();
        String newAddress=info[2].trim();

        UserDAO.updateAddress(newAddress,userName);
        //mainUI.add(userName+"修改地址");
        return "S";
    }

    //修改昵称
    public String updateNickName(String[] info){
        String userName=info[1].trim();
        String userNickName=info[2].trim();

        UserDAO.updateNickName(userNickName,userName);
        //mainUI.add(userName+"修改昵称");
        return "S";
    }
    //修改邮箱
    public String updateEmail(String[] info){
        String oldEmail=info[1].trim();
        String newEmail=info[2].trim();

        UserDAO.updateEmail(oldEmail,newEmail);
        //mainUI.add(oldEmail+"修改了邮箱");
        return "S";
    }
    //修改签名
    public String updateText(String[] info){
        String userName=info[1].trim();
        String text=info[2].trim();

        UserDAO.updateText(text,userName);
        //mainUI.add(userName+"修改了签名");
        return "S";
    }
    //改变余额
    public String updateMoney(String[] info){
        String userName=info[1].trim();
        String newMoney=info[2].trim();

        try {
            UserDAO.updateMoney(newMoney,userName);
            //mainUI.add(userName+"进行了充值");
            return "S";
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return "Error";
    }
    //向客户端发送用户的其他信息
    public String getMessage(String[] info){
        String userName=info[1].trim();
        ResultSet res=UserDAO.selectWithName(userName);
        try {
            while(res.next()){
                System.out.println(res.getString("user_nickName")+"/"+res.getString("user_text")+"/"+res.getString("user_address")+"/"+ res.getString("user_money")+"/"+res.getString("nowFoodNum"));
                return res.getString("user_nickName")+"/"+res.getString("user_text")+"/"+res.getString("user_address")+"/"+ res.getString("user_money")+"/"+res.getString("nowFoodNum")+"/ ";
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return "0";
    }

    //处理前端的支付操作
    public String Pay(String[] info){
        String userName=info[1].trim();
        String foodName=info[2].trim();
        String useMoney=info[3].trim();
        String useNumber=info[4].trim();

        double useMoneyStr=Double.parseDouble(useMoney);
        double newMoney=0-useMoneyStr;
        String newMoneyStr=Double.toString(newMoney);
        try {
            UserDAO.updateMoney(newMoneyStr,userName);
            FoodDAO.updateNumber(foodName,useNumber);
            FoodDAO.updateSale(foodName,useNumber);


            return "S";
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return "ERROR";
    }

    public String FoodShow(String[] info){
        String foodID=info[1].trim();
        ResultSet res=FoodDAO.selectWithFoodID(foodID);
        try{
            while(res.next()){
                String message=res.getString("food_value")+"/"+res.getString("food_sale")+"/"+res.getString("food_name")+"/"+res.getString("food_info")+"/"+res.getString("food_kind")+"/"+res.getString("food_number")+"/"+res.getString("food_url")+"/ ";
                System.out.println(message);
                return res.getString("food_value")+"/"+res.getString("food_sale")+"/"+res.getString("food_name")+"/"+res.getString("food_info")+"/"+res.getString("food_kind")+"/"+res.getString("food_number")+"/"+res.getString("food_url")+"/ ";
            }
        }catch (SQLException e){
            e.printStackTrace();
        }
        return "ERROR";
    }

    public String getRowOfFood(){
        int count=FoodDAO.getFoodCount();
        return "S/"+count+"/ ";
    }
    //向前端发送购物车内商品数量
    public String getCarFoodNum(String[] info){
        String userName=info[1].trim();
        return "S/"+UserDAO.getShopCarNum(userName)+"/ ";
    }

    //前端发来加入购物车的消息
    public String addShopCar(String[] info){
        String userName=info[1].trim();
        String foodName=info[2].trim();
        String currentCarNum=info[3].trim();


        UserDAO.addFoodToCar(userName,foodName,currentCarNum);
        return "S";
    }

   //
    public String getCarFoodInfo(String[] info){
        String userName=info[1].trim();
        String CarFoodNum=info[2].trim();
        String foodName=UserDAO.getCarFoodOfName(userName,CarFoodNum);
        ResultSet res1=UserDAO.selectWithName(userName);
        try{
            while(res1.next()){
                String str="food_"+CarFoodNum;
                if(res1.getString(str).equals("0"))
                    return "S/ ";
            }
        }catch (SQLException e){
            e.printStackTrace();
        }

        ResultSet res=FoodDAO.selectWithFoodName(foodName);
        try{
            while(res.next()){
                String message=res.getString("food_value")+"/"+res.getString("food_sale")+"/"+res.getString("food_name")+"/"+res.getString("food_info")+"/"+res.getString("food_kind")+"/"+res.getString("food_number")+"/"+res.getString("food_url")+"/ ";
                System.out.println(message);
                return res.getString("food_value")+"/"+res.getString("food_sale")+"/"+res.getString("food_name")+"/"+res.getString("food_info")+"/"+res.getString("food_kind")+"/"+res.getString("food_number")+"/"+res.getString("food_url")+"/ ";
            }
        }catch (SQLException e){
            e.printStackTrace();
        }
        return "ERROR";
    }

    //
    public String PayInShopCar(String[] info){
        String userName=info[1].trim();
        String foodName=info[2].trim();
        UserDAO.deleteForShopCar(userName,foodName);
        return "S";
    }

    public String getUrl(String[] info){
        String foodName=info[1].trim();
        ResultSet res=FoodDAO.selectWithFoodName(foodName);
        try{
            while(res.next()){
                return res.getString("food_url")+"X ";
            }
        }catch (SQLException e){
            e.printStackTrace();
        }
        return "ERROR";
    }
}

